package com.internetCafes.spms.common.AIRecognize.recognizer.impl;

import com.internetCafes.spms.common.AIRecognize.recognizer.Recognizer;
import com.internetCafes.spms.common.AIRecognize.QRCodeRecognizeUtils;
import com.internetCafes.spms.common.AIRecognize.analyzer.Analyzer;
import com.internetCafes.spms.common.AIRecognize.analyzer.AnalyzerManager;
import com.internetCafes.spms.common.AIRecognize.analyzer.impl.WordAnalyzer;
import com.internetCafes.spms.web.certificate.vo.AIRecognizeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * @author LinYe
 * @date 2020/10/14
 */
@Component
public class QRCodeRecognizer implements Recognizer {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    Pic2WordAIRecognizer pic2WordAIRecognizer;

    @Autowired
    WordAnalyzer wordAnalyzer;

    @Override
    public AIRecognizeInfo recognize(String filePath) {
        String scanResult = QRCodeRecognizeUtils.ScanQRCode(filePath);
        AnalyzerManager instance = AnalyzerManager.getInstance();
        Map<String, Analyzer> AllAnalyzers = applicationContext.getBeansOfType(Analyzer.class);
        Collection<Analyzer> values = AllAnalyzers.values();
        for (Iterator<Analyzer> iterator = values.iterator(); iterator.hasNext(); ) {
            Analyzer analyzer = iterator.next();
            instance.register(analyzer);
        }
        if (scanResult.contains("<CodeUrl>")) {
            scanResult = QRCodeRecognizeUtils.subPrefix(scanResult);
        }
        Analyzer analyzer = instance.getAnalyzer(scanResult);
        if (analyzer.getClass()== WordAnalyzer.class){
            return wordAnalyzer.analyze(scanResult,filePath);
        }else {
            AIRecognizeInfo aiRecognizeInfo = analyzer.analyze(scanResult, filePath);
            if (aiRecognizeInfo == null) {
                return pic2WordAIRecognizer.recognize(filePath);
            }
            return aiRecognizeInfo;
        }
    }
}
